import * as api from '@/services/idcOrder';
import { PageContainer } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Collapse, Divider, Popconfirm, Tag, Tooltip, message } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import * as utils from '@/utils/utils';
import * as c from '@/services/consts';
import Countdown from 'antd/es/statistic/Countdown';
import { ArrowDownOutlined, ArrowUpOutlined, ClockCircleOutlined, PlusOutlined, RedoOutlined, UserOutlined } from '@ant-design/icons';
const { Panel } = Collapse;
import BuyVpnServerForm from './BuyVpnServerForm'; 

const OrderList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const { hasRight } = useModel('useAuthModel');

  const [formCheckReportVisible, setFormCheckReportVisible] =useState<boolean>(false);
  const [formAutoCheckReportVisible, setFormAutoCheckReportVisible] =useState<boolean>(false);
  const [formCheckDomainVisible, setFormCheckDomainVisible] =useState<boolean>(false);
  const [formCheckManualVisible, setFormCheckManualVisible] =useState<boolean>(false);
  // const [formChangeCheckerVisible, setFormChangeCheckerVisible] =useState<boolean>(false);
  const [currentVer, setCurrentVer] = useState<string | undefined>(undefined);
  // const [checkType, setCheckType] =useState<string>('1');
  const [countdownTicks, setCountdownTicks] = useState<number>(Date.now() + 30000,);
  const [formBuyVisible, setFormBuyVisible] = useState<boolean>(false);
  
  const handleSubmit = async (ver: string | undefined) => {
    const result = await api.add({recheckId: ver});
    if (result && result.success) {
      actionRef?.current?.reload();
    }
  };
  
  const handleCheckDomainSubmit = async () => {
    setFormCheckDomainVisible(false);
    actionRef?.current?.reload();
  };
  
  const handleCheckManualSubmit = async () => {
    setFormCheckManualVisible(false);
    actionRef?.current?.reload();
  };

  const handleRemoveOrder = async (id: string | undefined) => {
    const result = await api.removeOrder({id});
    if (result && result.success) {
      actionRef?.current?.reload();
    }
  };

  const handlePublish = async (keys:string[]|undefined) => {
    // message.info('配置下发中');
    // const result = await api.publish({ keys : keys });
    // if (result && result.success === true) {
    //   message.success('配置下发成功');
    //   actionRef.current?.reload();
    //   return;
    // }
    // else{
    //   message.error('配置下发请求失败');
    // }
  };
    
  const reload = () => {
    actionRef.current?.reload();
    setCountdownTicks(Date.now() + 30000);
  };

  let columns: ProColumns<API.IdcOrder>[] = [
    {
      title: '状态',
      dataIndex: 'id',
      width: 200,
      sorter: true,
      render: (_, record) => {
        return (
          <>
          {record.status == c.IdcOrderStatus.Error.value ? <Tooltip title={record.idcMessage}><Tag color='#f50'><b>{c.IdcOrderStatus.Error.label}</b></Tag></Tooltip>
            : record.status == c.IdcOrderStatus.Pending.value ? <Tag color='#108ee9'><b>{c.IdcOrderStatus.Pending.label}</b></Tag>
            : record.status == c.IdcOrderStatus.Processing.value ? <Tag color='#108ee9'>{c.IdcOrderStatus.Processing.label}</Tag>
            : record.status == c.IdcOrderStatus.Done.value ? <Tag color='#87d068'>{c.IdcOrderStatus.Done.label}</Tag>
            : record.status == c.IdcOrderStatus.Close.value ? <Tag>{c.IdcOrderStatus.Close.label}</Tag>
            : <Tag>{record.status}</Tag>
          }
          <div style={{marginTop:5}}><Tag color={utils.getTextRanColor(`${record.idcType} ${c.getObjectText(c.IdcOrderType, record.orderType)}`)}>{record.idcType} {c.getObjectText(c.IdcOrderType, record.orderType)}</Tag></div>
          </>
        );
      },
    },
    
    {
      title: '检测内容',
      dataIndex: 'instanceIds',
      search: false,
      sorter: true,
      render: (_, record) => {
        return <>
        {/* <Divider orientation="left" orientationMargin={0}>产品信息</Divider> */}

        <Tag color='blue'>产品：<b>{record.configs?.idcIntro?.productName}</b> / {record.configs?.idcIntro?.region} / {record.configs?.idcIntro?.osName} / SSH Key：{record.configs?.idcIntro?.sshKeyName}</Tag>
        <Tag color='blue'>价格：<b>{record.configs?.idcIntro?.price / 100000000}</b> / {record.configs?.idcIntro?.currencyCode} / {record.configs?.idcIntro?.billing}</Tag>
        <Tag color='blue'>配置：{record.configs?.idcIntro?.cpus}核 / RAM：{record.configs?.idcIntro?.ram / 1000}G / Disk：{record.configs?.idcIntro?.disk / 1000}G</Tag>
        <Tag color='blue'>带宽：<ArrowDownOutlined />{record.configs?.idcIntro?.inboundBandwidth}M <ArrowUpOutlined />{record.configs?.idcIntro?.outboundBandwidth}M</Tag>

        
        <Collapse style={{marginBottom:10}} defaultActiveKey={['33']} ghost size='small'><Panel key="33" header={<><b>实例列表</b></>}>
        {record.servers ? <div style={{marginBottom:10}}>
          {record.servers.map((sid)=>{
          return <div style={{marginBottom:5}}>
            <Tag color={sid.status == c.IdcServerStatus.Complate.value ? 'success' 
            : sid.status == c.IdcServerStatus.Delete.value ? '' 
            : sid.status == c.IdcServerStatus.Error.value ? 'error' : sid.status == c.IdcServerStatus.Processing.value ? 'blue' : 'orange'
            }><b>{sid.instanceId}</b>&nbsp;&nbsp;[ {sid.idcServerName} ]
            {sid.ip ? <>&nbsp;&nbsp;&nbsp;IP: {sid.ip}</> : ''}
            </Tag>
          </div>
        })}</div> : ''}
        
        </Panel></Collapse>
        </>
      },
    },
    {
      title: '操作时间',
      dataIndex: 'id',
      width: 200,
      sorter: true,
      render: (_, record) => {
        return (
          <>
          {record.createUser ? <div style={{color:'#aaa'}}><UserOutlined /> {record.createUser}</div> : ''}
          {record.createTime ? <div style={{color:'#aaa'}}><ClockCircleOutlined /> {utils.formatDate(record.createTime)}</div> : ''}
          {record.updateTime ? <div style={{color:'#aaa'}}><ClockCircleOutlined /> {utils.formatDate(record.updateTime)}</div> : ''}
          </>
        );
      },
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 80,
      render: (_, record) => {
        let cmps = [];
        
        if (hasRight('idcorder_delete') && record.status != c.IdcOrderStatus.Close.value && record.status != c.IdcOrderStatus.Error.value) {
          cmps.push(
            <Popconfirm
              key="check_delete"
              title="确定要取消吗?"
              onConfirm={async () => {
                await handleRemoveOrder(record.id);
              }}
            >
              <a>取消</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        search={{
          defaultCollapsed: false,
        }}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        // toolbar={{
        //   multipleLine: true,
        //   menu: {
        //     type: 'tab',
        //     activeKey: checkType,
        //     items: [{label:'正常检测', key:'1'},{label:'定时检测', key:'2'}],
        //     onChange: (tabKey) => {
        //       setCheckType(`${tabKey}`);
        //     },
        //   },
        // }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];

          if (hasRight('idcorder_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="buy_ovh"
                onClick={() => {
                  setFormBuyVisible(true);
                }}
              >
              <PlusOutlined />
               OVH购买
              </Button>
            ]);
          }

          if (hasRight('idcorder_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="create_check_domain"
                onClick={() => {
                  setFormCheckDomainVisible(true);
                }}
              >
               域名检测
              </Button>
            ]);
          }

          
          if (hasRight('idcorder_update')) {
            toolbarDoms.push([
              <Button
                type="primary"
                danger
                key="checktask_publish"
                onClick={async() => {
                  await handlePublish(undefined);
                }}
              >
               下发配置
              </Button>
            ]);
          }

          toolbarDoms.push([
            <span>
            <Countdown
              title=""
              key="cdRefresh"
              value={countdownTicks}
              format="s"
              prefix=""
              suffix="秒后刷新"
              valueStyle={{
                fontSize: 14,
                color: 'gray',
              }}
              onFinish={reload}
            />
          </span>
          ]);

          return toolbarDoms;
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 30,
          pageSizeOptions: ['15', '30', '60', '100'],
          hideOnSinglePage: true,
        }}
        request={api.list}
      />

      
      
      <BuyVpnServerForm
        visible={formBuyVisible}
        onCancel={() => {
          setFormBuyVisible(false);
        }}
      />

    </PageContainer>
  );
};

export default OrderList;
